namespace Gateway.Common.Extensions;

public static class ObjectExtensions
{
    /// <summary>
    /// 将object转换为long，若失败则返回0
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static long ParseToLong(this object obj)
    {
        try
        {
            return long.Parse(obj.ToString());
        }
        catch
        {
            return 0L;
        }
    }
    
    /// <summary>
    /// 将object转换为double，若失败则返回0
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static double ParseToDouble(this object obj)
    {
        try
        {
            return double.Parse(obj.ToString());
        }
        catch
        {
            return 0;
        }
    }
    
    
    public static string ToHumanReadableSize(this long size)
    {
        const double KB = 1.0;
        const double MB = KB * 1024;
        const double GB = MB * 1024;

        if (size < MB)
            return size + " KB";
        else if (size < GB)
            return (size / MB).ToString("0.##") + " MB";
        else
            return (size / GB).ToString("0.##") + " GB";
    }
}